<template>
  <base-page-view class-name="page-container promotion-container">
    <!-- <b-image v-for="(item, index) in 11" :key="index" class-name="img-item" :src="'/static/images/promotion/promotion_'+index+'.jpg'" mode="widthFix" :is-asset="true" /> -->
    <view class="img-list">
      <image v-for="(item, index) in 13" :key="index" class="img-item" :src="IMAGE_ASSET + '/images/promotion/promotion_'+index+'.jpg'" mode="widthFix" />
    </view>
    <image class="share-btn" :src="showIcon" mode="aspectFit" @click="toShare" />
    <canvas canvas-id="myCanvas" :style="'width: '+poster.width+'px; height: '+poster.height+'px;'"></canvas>
    <view class="footer-block">
      <view class="sub-item" :style="'background-image: url('+footerBarShare+')'" @click="toShare"></view>
      <view class="sub-item" :style="'background-image: url('+footerBarBuy+')'" @click="toBuy"></view>
    </view>
    <view class="share-pop" :class="{ active: showSharePop }">
      <view class="sub-item">
        <view class="poster">
          <image class="bg" :src="poster.result" mode="aspectFit" />
        </view>
      </view>
      <view class="type-block">
        <view class="type-btn-list">
          <view class="type-item" @click="saveImage">
            <image :src="shareIcon" mode="aspectFit" />
            <view>保存图片</view>
          </view>
        </view>
        <view class="btn-footer" @click="close(true)">取 消</view>
      </view>
    </view>
    <!-- #ifdef H5 -->
    <view style="width:0;height:0;overflow:hidden;transform: translateX(-100%)">
      <tki-qrcode ref="qrcode" :val="shareShortUrl" :size="400" :unit="'upx'" :show-loading="false" @result="initShareImg" />
    </view>
    <!--  #endif -->
  </base-page-view>
</template>
<script>
import { mapState } from 'vuex'
import tkiQrcode from 'tki-qrcode'
import { createSharePathUrl } from '@/utils/tools'
import './index.scss'
export default {
  components: {
    tkiQrcode
  },
  data() {
    return {
      ctx: null,
      IMAGE_ASSET: process.env.VUE_APP_IMAGE_ASSET,
      showIcon: `${process.env.VUE_APP_IMAGE_ASSET}/images/promotion/icon_share.png`,
      shareBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/promotion/poster_bg.png`,
      footerBarShare: `${process.env.VUE_APP_IMAGE_ASSET}/images/promotion/footer_share_btn.png`,
      footerBarBuy: `${process.env.VUE_APP_IMAGE_ASSET}/images/promotion/footer_buy_btn.png`,
      shareIcon: `${process.env.VUE_APP_IMAGE_ASSET}/images/share/icon_share_02.png`,
      showSharePop: false,
      shareMiniCode: '',
      shareShortUrl: '',
      avatarWidth: 100,
      avatarHeight: 100,
      poster: {
        width: 375,
        height: 667,
        bg: '',
        avatar: '',
        miniCode: '',
        result: ''
      }
    }
  },
  computed: {
    ...mapState([
      'token',
      'userInfo'
    ])
  },
  created() {
    // this.initPoster()
  },
  onLoad() {
  },
  onShow() {
    this.initPoster()
  },
  methods: {
    initPoster() {
      this.ctx = uni.createCanvasContext('myCanvas', this)
      // #ifdef MP-WEIXIN
      this.getMiniCode()
      // #endif

      // #ifdef H5
      this.getQrCode()
      // #endif

      this.getImageInfo('bg', this.shareBg)
      this.poster.avatar = ''
      if (this.userInfo.head_img) {
        this.getImageInfo('avatar', this.userInfo.head_img)
      } else {
        this.poster.avatar = '/static/images/mine/touxiang.png'
      }
    },
    async getQrCode() {
      // #ifdef H5
      if (!this.shareShortUrl && this.token) {
        const path = createSharePathUrl()
        const url = location.origin + '/pages/share/index?path=' + encodeURIComponent(path)
        const res = await this.$api.goodsApi.shortUrl({
          longurl: url
        })
        this.shareShortUrl = res.data || url
      }
      setTimeout(() => {
        if (this.shareShortUrl) {
          this.$refs.qrcode._makeCode()
        }
      }, 100)
      // #endif
    },
    initShareImg(val) {
      this.poster.miniCode = val
    },
    async getMiniCode() {
      if (!this.shareMiniCode && this.token) {
        const path = createSharePathUrl()
        console.log(path)
        const res = await this.$api.commonApi.queryMiniCode({
          page: 'pages/share/index',
          scene: encodeURIComponent(path),
          width: 430
        })
        if (res.success && res.data) {
          this.shareMiniCode = res.data.file_path
        }
      }
      this.getImageInfo('miniCode', this.shareMiniCode)
    },
    getImageInfo(key, src, fn) {
      if (this.poster[key]) {
        if (fn) {
          fn()
        }
      } else {
        uni.getImageInfo({
          src,
          success: (res) => {
            this.poster[key] = res.path
            if (key === 'avatar') {
              this.avatarWidth = res.width
              this.avatarHeight = res.height
            }
            if (fn) {
              fn()
            }
          },
          fail: (res) => {
            console.log(key, src, res)
          }
        })
      }
    },
    getTextWidth(text, fontSize = 22) {
      this.ctx.font = `${fontSize}px sans-serif`
      return this.ctx.measureText(text).width
    },
    generateImg() {
      if (this.poster.result) {
        // #ifdef H5
        this.saveImage()
        // #endif
        // #ifdef MP-WEIXIN
        uni.hideLoading()
        this.showSharePop = true
        // #endif
        return
      }
      uni.showLoading({
        title: '海报生成中...'
      })
      // 背景
      this.ctx.rect(0, 0, this.poster.width, this.poster.height)
      this.ctx.setFillStyle('white')
      this.ctx.fill()
      this.ctx.drawImage(this.poster.bg, 0, 0, this.poster.width, this.poster.height)

      // 头像
      const yPosition = this.poster.height - 70
      this.ctx.save()
      this.ctx.beginPath()
      this.ctx.arc(43.5, yPosition, 27, 0, 2 * Math.PI)
      this.ctx.setFillStyle('white')
      this.ctx.fill()
      this.ctx.clip()
      if (this.avatarWidth === this.avatarHeight) {
        this.ctx.drawImage(this.poster.avatar, 15, yPosition - 27, 54, 54)
      } else {
        const sx = (this.avatarWidth > this.avatarHeight) ? (this.avatarWidth - this.avatarHeight) / 2 : 0
        const sy = (this.avatarWidth > this.avatarHeight) ? 0 : (this.avatarHeight - this.avatarWidth) / 2
        const size = (this.avatarWidth > this.avatarHeight) ? this.avatarHeight : this.avatarWidth
        this.ctx.drawImage(this.poster.avatar, sx, sy, size, size, 15, yPosition - 27, 54, 54)
      }
      this.ctx.stroke()
      this.ctx.restore()

      // 昵称
      this.ctx.setFontSize(15)
      this.ctx.setFillStyle('#999')
      this.ctx.fillText(this.userInfo.nickname, 80, yPosition - 10)
      this.ctx.setFontSize(14)
      this.ctx.setFillStyle('#000')
      this.ctx.fillText('我已下单抢到啦!', 80, yPosition + 15)
      this.ctx.fillText('限时活动，快去抢!', 80, yPosition + 35)

      // 小程序码
      this.ctx.drawImage(this.poster.miniCode, this.poster.width - 116, yPosition - 54, 96, 96)

      this.ctx.setFontSize(14)
      this.ctx.setFillStyle('#999')
      this.ctx.fillText('扫码速抢!', this.poster.width - 100, yPosition + 60)

      this.ctx.draw(false, () => {
        setTimeout(() => {
          uni.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: (res) => {
              this.poster.result = res.tempFilePath
              // #ifdef H5
              this.saveImage()
              // #endif
              // #ifdef MP-WEIXIN
              uni.hideLoading()
              this.showSharePop = true
              // #endif
            },
            fail: (res) => {
              console.log(res)
              uni.hideLoading()
            }
          }, this)
        }, 800)
      })
    },
    saveImage() {
      // #ifdef H5
      uni.previewImage({
        current: this.poster.result,
        urls: [this.poster.result],
        success() {
          setTimeout(() => {
            uni.showToast({ title: '长按保存图片到相册再分享', icon: 'none', duration: 3000 })
          }, 500)
        }
      })
      // #endif

      // #ifdef MP-WEIXIN
      uni.saveImageToPhotosAlbum({
        filePath: this.poster.result,
        success: () => {
          uni.showToast({
            title: '已成功保存到系统相册',
            icon: 'none'
          })
          this.close()
        },
        fail: (res) => {
          console.log(res)
          uni.hideLoading()
        }
      })
      // #endif
    },
    close(sensorFlag) {
      this.showSharePop = false
      if (sensorFlag) {
        this.$sensorTrack('CLICKBUTTON', {
          page_name: 'h5_gift',
          button_name: 'cancel'
        })
      }
    },
    toShare() {
      this.$sensorTrack('CLICKBUTTON', {
        page_name: 'h5_gift',
        button_name: 'share',
        login_status: this.token ? 1 : 0
      })
      if (this.token) {
        this.generateImg()
      } else {
        this.$navigateTo('/pages/login/index')
      }
    },
    toBuy() {
      this.$sensorTrack('CLICKBUTTON', {
        page_name: 'h5_gift',
        button_name: 'submit_order'
      })
      this.$navigateTo('/pagesOrder/promotion/orderCheck')
    }
  }
}
</script>
